package com.terren.schelude.work;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.collections.CollectionUtils;

import com.terren.common.entity.Article;
import com.terren.common.util.CommonUtil;
import com.terren.config.SysConfig;
import com.terren.db.service.ArticleService;

public class ArticleWork extends BasicWork implements Runnable {
	public ArticleWork(CountDownLatch countDownLatch){
		super();
        this.countDownLatch = countDownLatch;
       
    }
    @Override
    public void run() {
    	ArticleService articleService = CommonUtil.getBean(ArticleService.class);
        try {
            log.info(Thread.currentThread().getName() + "启动@" + System.currentTimeMillis());
            while(true) {
            	Article art = new Article();
            	art.setLimit(SysConfig.LIMIT);
            	List<Article> list = articleService.getArticleList(art);
            	if(CollectionUtils.isEmpty(list)) {
            		break;
            	}
        		List<Article> dealList = new ArrayList<Article>();
        		int total = list.size();
        		int i = 1;
        		for(Article a : list) {
        			//调接口
        			log.info("当前第 "+i+"篇搜索文章正在调用接口,本轮共计"+total+"篇搜索文章");
        			i++;
        			List<String> keywords = articleService.getKeywords(a);
        			if(CollectionUtils.isNotEmpty(keywords)) {
        				Boolean flag = CommonUtil.keywords(a.getContent(),keywords);
            			if(flag) {
            				Integer score = getScore(a.getContent());
                			if(score !=-1 && findKeyword(a.getContent(), set)) {
                				a.setOpinion_analysis(score);
                				StringBuilder sb = new StringBuilder();
                				int m = keywords.size();
                				for(int k=1;k<=m;k++) {
                					if(k==m) {
                						sb.append(keywords.get(k-1));	
                					}else {
                						sb.append(keywords.get(k-1)).append(",");
                					}
                					
                				}
                				a.setKeyword(sb.toString());
                				dealList.add(a);
                			}
            			}
        			}
        		}
        		if(CollectionUtils.isNotEmpty(dealList)) {
        			opinionAnalysisService.saveArticles(dealList);
        		}
        		articleService.updateDoneStatus(list);
            }  
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	if(countDownLatch !=null)
        		countDownLatch.countDown();
        	log.info("搜索文章调用接口完成......");
		}
    }
}
